<template>
  <div class="notification-center-container">
    <div class="notification-center">
      <!-- 头部 -->
      <div class="header">
        <h1 class="title">
          <el-icon class="title-icon"><BellFilled /></el-icon>
          消息中心
        </h1>
        <div class="actions">
          <el-button
            type="danger"
            :disabled="selectedIds.length === 0"
            @click="batchMarkAsRead"
          >
            <el-icon><CircleCheck /></el-icon>
            标记已读
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedIds.length === 0"
            @click="batchDelete"
          >
            <el-icon><Delete /></el-icon>
            删除选中
          </el-button>
        </div>
      </div>

      <!-- 过滤栏 -->
      <div class="filter-bar">
        <div class="notification-filters">
          <div class="button-group">
            <el-button
              :type="activeFilter === 'all' ? 'danger' : 'default'"
              @click="activeFilter = 'all'"
              style="width:15%"
            >
              全部
            </el-button>
            <el-button
              :type="activeFilter === 'unread' ? 'danger' : 'default'"
              @click="activeFilter = 'unread'"
              style="width:15%"
            >
              未读
            </el-button>
            <el-button
              :type="activeFilter === 'system' ? 'danger' : 'default'"
              @click="activeFilter = 'system'"
              style="width:15%"
            >
              系统
            </el-button>
            <el-button
              :type="activeFilter === 'warning' ? 'danger' : 'default'"
              @click="activeFilter = 'warning'"
              style="width:15%"
            >
              警告
            </el-button>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索消息..."
              clearable
              @input="handleSearch"
              style="width:15%;"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </div>

      <!-- 消息列表 -->
      <el-scrollbar class="notification-list">
        <el-checkbox-group v-model="selectedIds">
          <div
            v-for="notification in paginatedNotifications"
            :key="notification.id"
            :class="['notification-item', { unread: !notification.read }]"
          >
            <el-checkbox
              class="item-checkbox"
            />
            <div class="item-content" @click="viewDetail(notification)">
              <div class="item-icon" :class="notification.type">
                <el-icon v-if="notification.type === 'system'"><BellFilled /></el-icon>
                <el-icon v-if="notification.type === 'warning'"><WarningFilled /></el-icon>
                <el-icon v-if="notification.type === 'emergency'"><Promotion /></el-icon>
              </div>
              <div class="item-details">
                <div class="item-header">
                  <span class="item-title">{{ notification.title }}</span>
                  <div class="item-meta">
                    <span class="item-time">
                      <el-icon><Clock /></el-icon>
                      {{ formatTime(notification.timestamp) }}
                    </span>
                    <el-tag
                      v-if="!notification.read"
                      type="danger"
                      effect="plain"
                      size="small"
                      class="unread-tag"
                    >
                      未读
                    </el-tag>
                  </div>
                </div>
                <p class="item-description">{{ notification.content }}</p>
              </div>
              <div class="item-actions">
                <el-button
                  link
                  type="danger"
                  @click.stop="toggleReadStatus(notification)"
                >
                  {{ notification.read ? '标记未读' : '标记已读' }}
                </el-button>
                <el-button
                  link
                  type="danger"
                  @click.stop="deleteNotification(notification.id)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </el-checkbox-group>

        <!-- 空状态 -->
        <div v-if="filteredNotifications.length === 0" class="empty-state">
          <el-icon class="empty-icon"><ChatLineRound /></el-icon>
          <p class="empty-text">暂无相关消息</p>
        </div>
      </el-scrollbar>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalItems"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          background
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  BellFilled,
  WarningFilled,
  Promotion,
  CircleCheck,
  Delete,
  Search,
  Clock,
  ChatLineRound
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'

// 配置中文时间显示
dayjs.locale('zh-cn')
dayjs.extend(relativeTime)

interface Notification {
  id: string
  title: string
  content: string
  type: 'system' | 'warning' | 'emergency'
  timestamp: number
  read: boolean
}

const STORAGE_KEY = 'app_notifications'
const router = useRouter()

// 状态管理
const notifications = ref<Notification[]>([])
const activeFilter = ref<'all' | 'unread' | 'system' | 'warning'>('all')
const searchKeyword = ref('')
const selectedIds = ref<string[]>([])
const currentPage = ref(1)
const pageSize = ref(10)

// 加载数据
onMounted(() => {
  loadNotifications()
})

const loadNotifications = () => {
  const saved = localStorage.getItem(STORAGE_KEY)
  notifications.value = saved ? JSON.parse(saved) : []
}

// 数据过滤
const filteredNotifications = computed(() => {
  return notifications.value.filter(n => {
    // 类型过滤
    const typeMatch = activeFilter.value === 'all' ||
      (activeFilter.value === 'unread' ? !n.read : n.type === activeFilter.value)

    // 搜索过滤
    const searchMatch = !searchKeyword.value ||
      n.title.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      n.content.toLowerCase().includes(searchKeyword.value.toLowerCase())

    return typeMatch && searchMatch
  }).sort((a, b) => b.timestamp - a.timestamp)
})

// 分页数据
const totalItems = computed(() => filteredNotifications.value.length)
const paginatedNotifications = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredNotifications.value.slice(start, end)
})

// 时间格式化（中文）
const formatTime = (timestamp: number) => {
  const now = dayjs()
  const target = dayjs(timestamp)

  if (now.diff(target, 'hour') < 24) return target.fromNow()
  return target.format('YYYY-MM-DD HH:mm')
}

// 操作处理
const toggleReadStatus = (notification: Notification) => {
  notification.read = !notification.read
  saveNotifications()
}

const deleteNotification = (id: string) => {
  notifications.value = notifications.value.filter(n => n.id !== id)
  saveNotifications()
}

const batchMarkAsRead = () => {
  notifications.value = notifications.value.map(n =>
    selectedIds.value.includes(n.id) ? { ...n, read: true } : n
  )
  selectedIds.value = []
  saveNotifications()
}

const batchDelete = () => {
  notifications.value = notifications.value.filter(
    n => !selectedIds.value.includes(n.id)
  )
  selectedIds.value = []
  saveNotifications()
}

const viewDetail = (notification: Notification) => {
  router.push(`/notifications/${notification.id}`)
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 数据持久化
const saveNotifications = () => {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(notifications.value))
}
</script>

<style lang="scss" scoped>
.notification-center-container {
  width: 100%;
  height: 100%;
  overflow: hidden;

  .notification-center {
    display: flex;
    flex-direction: column;
    height: 100%;
    max-width: 100%;
    padding: 24px;
    background: var(--background-color);
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      padding-bottom: 16px;
      border-bottom: 1px solid var(--el-border-color-light);

      .title {
        display: flex;
        align-items: center;
        margin: 0;
        font-size: 24px;
        color: var(--el-text-color-primary);

        .title-icon {
          color: var(--el-color-danger);
          font-size: 32px;
          margin-right: 12px;
        }
      }

      .actions {
        display: flex;
        gap: 12px;
      }
    }

    .filter-bar {
      display: flex;
      flex-direction: column;
      margin-bottom: 24px;

      .notification-filters {
        .button-group {
          display: flex;
          gap: 16px;
        }
      }
    }

    .notification-list {
      flex: 1;
      min-height: 0;
      border: 1px solid var(--el-border-color-light);
      border-radius: 8px;

      .notification-item {
        display: flex;
        align-items: center;
        padding: 16px 24px;
        border-bottom: 1px solid var(--el-border-color-lighter);
        transition: all 0.3s;

        &:hover {
          background: var(--el-color-danger-light-9);
        }

        &.unread {
          border-left: 3px solid var(--el-color-danger);
        }

        .item-checkbox {
          margin-right: 16px;
        }

        .item-content {
          flex: 1;
          display: flex;
          align-items: center;
          gap: 16px;
          cursor: pointer;

          .item-icon {
            flex-shrink: 0;
            width: 40px;
            height: 40px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;

            &.system {
              background: var(--el-color-primary-light-9);
              color: var(--el-color-primary);
            }

            &.warning {
              background: var(--el-color-warning-light-9);
              color: var(--el-color-warning);
            }

            &.emergency {
              background: var(--el-color-danger-light-9);
              color: var(--el-color-danger);
            }

            .el-icon {
              font-size: 20px;
            }
          }

          .item-details {
            flex: 1;

            .item-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 8px;

              .item-title {
                font-weight: 600;
                font-size: 16px;
                color: var(--el-text-color-primary);
              }

              .item-meta {
                display: flex;
                align-items: center;
                gap: 12px;

                .item-time {
                  display: flex;
                  align-items: center;
                  gap: 4px;
                  color: var(--el-text-color-secondary);
                  font-size: 14px;

                  .el-icon {
                    font-size: 14px;
                  }
                }
              }
            }

            .item-description {
              color: var(--el-text-color-regular);
              font-size: 14px;
              line-height: 1.5;
              margin: 0;
            }
          }

          .item-actions {
            flex-shrink: 0;
            display: flex;
            gap: 12px;
            margin-left: 24px;
          }
        }
      }

      .empty-state {
        padding: 80px 0;
        text-align: center;

        .empty-icon {
          font-size: 64px;
          color: var(--el-color-danger-light-5);
          margin-bottom: 16px;
        }

        .empty-text {
          color: var(--el-text-color-secondary);
          margin: 0;
          font-size: 16px;
        }
      }
    }

    .pagination {
      margin-top: 24px;
      display: flex;
      justify-content: center;
      padding: 16px 0;
    }
  }
}
.el-checkbox {
  margin: 0;
  --el-checkbox-border-color: var(--danger-border);
  --el-checkbox-checked-border-color: var(--danger-main);
  --el-checkbox-checked-bg-color: #f5222d;
  --el-checkbox-checked-input-border-color: #f5222d;
  --el-checkbox-checked-text-color: var(--danger-text);
  --el-checkbox-input-border-color-hover: #f5222d;

  .el-checkbox__label {
    display: flex;
    align-items: center;
  }

  .checkbox-icon {
    margin-right: 8px;
    font-size: 16px;
    color: var(--danger-light);
  }

  &.is-checked {
    border-color: var(--danger-main);

    .checkbox-icon {
      color: var(--danger-main);
    }
  }
}
</style>
